package com.tianpengtech.common.im.kit;

import java.util.Date;
import java.util.Set;

import org.tio.core.Aio;
import org.tio.core.ChannelContext;
import org.tio.core.ObjWithLock;
import org.tio.server.ServerGroupContext;

import com.jfinal.plugin.activerecord.Db;
import com.jfinal.plugin.activerecord.Record;
import com.tianpengtech.common.im.common.ImPacket;
import com.tianpengtech.common.im.common.ImSessionContext;
import com.tianpengtech.common.im.common.pockets.ChatRespBody;
import com.tianpengtech.common.im.common.pockets.ChatType;
import com.tianpengtech.common.im.common.pockets.Command;
import com.tianpengtech.common.util.DateUtils;


public class PushKit {

	
	public final static String push_MSG_GROUP="sys";
	public static ServerGroupContext<ImSessionContext, ImPacket, Object> serverGroupContext = null;

	/**
	 * 发送群体消息
	 * @param group
	 * @param respPacket
	 */
	public static void  pushGroupMessage(String group,ImPacket respPacket){
		
		ObjWithLock<Set<ChannelContext<ImSessionContext, ImPacket, Object>>> channelList = Aio.getChannelContextsByGroup(serverGroupContext, group);
		if(channelList!=null){
			Set<ChannelContext<ImSessionContext, ImPacket, Object>> d = channelList.getObj();
			for (ChannelContext<ImSessionContext, ImPacket, Object> channelContext : d) {
				Aio.sendToGroup(channelContext.getGroupContext(), group, respPacket);
			}
		}
	}
	
	/**
	 * 推送系统消息
	 * @param content
	 */
	public static void pushSystemMessage(String content){
		ChatRespBody.Builder builder = ChatRespBody.newBuilder();
		builder.setType(ChatType.CHAT_TYPE_PUBLIC);
		builder.setGroup(push_MSG_GROUP);
		builder.setText(content);
		builder.setTime(new Date().getTime());
		ChatRespBody chatRespBody = builder.build();
		byte[] bodybyte = chatRespBody.toByteArray();
		ImPacket respPacket = new ImPacket();
		respPacket.setCommand(Command.COMMAND_SYS_MESSAGE_RESP);
		respPacket.setBody(bodybyte);
		pushGroupMessage(push_MSG_GROUP, respPacket);
	}
	
	
	public static void pushSystemMessageNow(String content){
		String msg = content;
		content = content+" "+DateUtils.formateData(new Date(), DateUtils.YYMMDDHHMMSS_FORMAT);
		pushSystemMessage(content);
		Record record = new Record();
		record.set("msg", msg);
		Db.save("fair_message", record);
	}
}
